
public class ThreadsPool implements Runnable{

    private BlockingQueue<Runnable> queue = null;

    public ThreadsPool(int size) {
        assert size > 0;
        queue = new BlockingQueue<Runnable>(size);
        new Thread(this).start();
    }

    public void execute(Runnable task) {
        try {
            queue.enqueue(task);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        while (true) {
            try {
                Runnable r = queue.dequeue();
                new Thread(r).start();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        ThreadsPool pool = new ThreadsPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable r = new Runnable() {
                
                @Override
                public void run() {
                    try {
                        Thread.currentThread().sleep(1000);
                        System.out.println(Thread.currentThread().getId() + ": hi");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }
            };
            pool.execute(r);
        }
    }
}
